package org.teremail.delivery;

import java.util.Set;

import org.teremail.mailbox.Mailbox;
import org.teremail.mailbox.MailboxNotExistsException;
import org.teremail.mailbox.MailboxService;
import org.teremail.message.Address;

/**
 * Handles the delivery of messages to their mailboxes.
 * 
 * TODO: We need to track which messages have been delivered.
 * 
 * @author Michael Barker
 *
 */
public class DeliveryHandler implements MessageHandler {

    private final MailboxService mailboxService;
    private final Set<String> domains;
    private final MessageHandler next;

    public DeliveryHandler(MailboxService ms, Set<String> domains) {
        this(ms, domains, NullHandler.create());
    }

    public DeliveryHandler(MailboxService ms, Set<String> domains,
            MessageHandler next) {
        this.mailboxService = ms;
        this.domains = domains;
        this.next = next;
    }

    public void handle(Envelope envelope) {
        for (final Address recipient : envelope.getRecipients()) {
            if (domains.contains(recipient.getDomain())) {
                try {
                    Mailbox mbox = mailboxService.getMailbox(recipient.getUser());
                    mbox.deliver(envelope.getMessage());
                } catch (MailboxNotExistsException e) {
                    // TODO: Bounce message.
                    throw new RuntimeException(e);
                }
            }
        }
        
        next.handle(envelope);
    }

}
